package ace.cmp.security.core.impl.model.principal;

import ace.cmp.security.core.impl.model.dto.AceIntrospectPrincipalDto;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * @author caspar
 * @date 2023/8/1 15:19 ACE 架构 oauth2 认证的 principal
 */
public class AceDefaultOauth2AuthenticatedPrincipal<T extends AceIntrospectPrincipalDto>
    implements AceOauth2AuthenticatedPrincipal<T> {
  private final T principal;
  private Collection<? extends GrantedAuthority> authorities;

  public AceDefaultOauth2AuthenticatedPrincipal(T principal) {
    this.principal = principal;
    this.authorities =
        Stream.ofNullable(principal.getAuthorities())
            .flatMap(Set::stream)
            .map(p -> new SimpleGrantedAuthority(p))
            .collect(Collectors.toSet());
  }

  @Override
  public T getPrincipal() {
    return this.principal;
  }

  @Override
  public Map<String, Object> getAttributes() {
    return this.principal.getAttributes();
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return this.authorities;
  }

  @Override
  public String getName() {
    return this.principal.getId();
  }
}
